package com.happyhome.services;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.happyhome.constants.ComTxManagerName;
import com.happyhome.dao.ImageDao;
import com.happyhome.datamodel.Image;

@Service
public class ImageServiceImpl implements ImageService{
	
	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory.getLogger(ImageServiceImpl.class);
	
	@Autowired
    private ImageDao imageDao;

	@Override
	@Transactional(value = ComTxManagerName.COM_TRANSACTION_MANAGER)
	public Image merge(Image image) {
		return imageDao.merge(image);
	}

	@Override
	public Image getImageById(Long id) {
		Image image = imageDao.find(id);
		return image;
	}

	@Override
	@Transactional(value = ComTxManagerName.COM_TRANSACTION_MANAGER)
	public void deleteImageById(Long id) {
		imageDao.removeById(id);		
	}

	@Override
	@Transactional(value = ComTxManagerName.COM_TRANSACTION_MANAGER)
	public void deleteImage(Image image) {
		imageDao.remove(image);
	}

	@Override
	public List<Image> getAllImagesByHouseId(Long houseId) {
		return imageDao.getAllImagesByHouseId(houseId);
	}

	@Override
	public List<Image> getAllImagesByRoomId(Long roomId) {
		return imageDao.getAllImagesByRoomId(roomId);
	}
	
	@Override
	public List<Image> getAllImagesFree(){
		return imageDao.getAllImagesFree();
	}

	@Override
	public Image getImageByNewFileName(String fileName) {
		return imageDao.getImageByNewFileName(fileName);
	}

	@Override
	public List<Image> getListImageByAId(Long aId, String type) {
		return imageDao.getListImageByAId(aId, type);
	}

	@Override
	public Image getImageByAIdIsDisplay(Long aId, String type) {
		return imageDao.getImageByAIdIsDisplay(aId, type);
	}

	@Override
	public Image getImageNewestAId(Long aId, String type) {
		return imageDao.getImageNewestAId(aId, type);
	}

	@Override
	@Transactional(value = ComTxManagerName.COM_TRANSACTION_MANAGER)
	public void markImageFormSubmit(Long imageId, String type) {
		Image imageTarget = imageDao.find(imageId);
		if(imageTarget != null && imageTarget.getHouse() != null){
			List<Image> listImages = imageDao.getListImageByAId(imageTarget.getHouse().getIdHouse(), type);
			if(listImages != null && listImages.size() > 0){
				for(Image image : listImages){
					if(image.getId() != imageTarget.getId()){
						image.setIsDisplay(Boolean.valueOf("false"));
					}else{
						image.setIsDisplay(Boolean.valueOf("true"));
					}
				}
			}
		}
		imageDao.flush();
	}
}
